import React, { useState, useEffect } from 'react';
import { Box, Typography, Card, CardContent, Grid, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, Chip, Alert, CircularProgress, Dialog, DialogTitle, DialogContent, DialogActions, TextField, FormControl, InputLabel, Select, MenuItem } from '@mui/material';
import { Warning, CheckCircle, Error, Info, Refresh, Search, FilterList } from '@mui/icons-material';
import { apiRequest } from '../utils/api';

const EmergencyAlerts = () => {
  const [alerts, setAlerts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userData, setUserData] = useState(null);
  const [selectedAlert, setSelectedAlert] = useState(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      try {
        setUserData(JSON.parse(savedUserInfo));
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }
    loadAlerts();
  }, []);

  const loadAlerts = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await apiRequest.get('/api/alerts');
      setAlerts(response.data);
    } catch (err) {
      console.error('Failed to load emergency alerts:', err);
      setError('加载紧急警报失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleResolveAlert = async (alertId) => {
    try {
      await apiRequest.put(`/api/alerts/${alertId}/resolve`);
      await loadAlerts();
      setOpenDialog(false);
    } catch (err) {
      console.error('Failed to resolve alert:', err);
      setError('处理警报失败，请稍后重试');
    }
  };

  // 格式化警报类型显示
  const formatAlertType = (alertType) => {
    if (!alertType) return '';
    
    const typeMap = {
      'THEFT_ATTEMPT': '盗窃尝试',
      'ENGINE_FAILURE': '引擎故障',
      'BRAKE_SYSTEM_FAILURE': '刹车系统故障',
      'AIRBAG_DEPLOYMENT': '安全气囊展开',
      'COLLISION_DETECTED': '碰撞检测',
      'ENGINE_OVERHEAT': '引擎过热',
      'BATTERY_LOW': '电池电量低',
      'TIRE_PRESSURE_CRITICAL': '轮胎压力临界',
      'FUEL_EMPTY': '燃油耗尽',
      'DOOR_OPEN': '车门未关',
      'WINDOW_OPEN': '车窗未关',
      'LIGHTS_ON': '车灯未关',
      'TIRE_PRESSURE_LOW': '轮胎压力低'
    };
    
    return typeMap[alertType] || alertType.replace('_', ' ').toLowerCase();
  };
  
  // 格式化严重程度显示
  const formatSeverity = (severity) => {
    if (!severity) return '未知';
    
    const severityMap = {
      'HIGH': '高',
      'MEDIUM': '中',
      'LOW': '低'
    };
    
    return severityMap[severity] || severity;
  };
  
  const getSeverityColor = (severity) => {
    switch (severity) {
      case 'HIGH': return 'error';
      case 'MEDIUM': return 'warning';
      case 'LOW': return 'info';
      default: return 'default';
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'ACTIVE': return 'error';
      case 'RESOLVED': return 'success';
      case 'PENDING': return 'warning';
      default: return 'default';
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'ACTIVE': return <Warning color="error" />;
      case 'RESOLVED': return <CheckCircle color="success" />;
      case 'PENDING': return <Info color="warning" />;
      default: return <Info />;
    }
  };

  const filteredAlerts = alerts.filter(alert => {
    const matchesStatus = statusFilter === 'ALL' || alert.status === statusFilter;
    const matchesSearch = searchTerm === '' || 
      (alert.alertType && alert.alertType.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (alert.description && alert.description.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (alert.vehicleId && alert.vehicleId.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (alert.vehiclePlate && alert.vehiclePlate.toLowerCase().includes(searchTerm.toLowerCase()));
    return matchesStatus && matchesSearch;
  });

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h4" gutterBottom>
          紧急警报管理
        </Typography>
        <Button
          variant="contained"
          color="primary"
          startIcon={<Refresh />}
          onClick={loadAlerts}
        >
          刷新
        </Button>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3}>
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                统计概览
              </Typography>
              <Box display="flex" flexDirection="column" gap={2}>
                <Box display="flex" justifyContent="space-between">
                  <Typography>总警报数:</Typography>
                  <Typography variant="h6">{alerts.length}</Typography>
                </Box>
                <Box display="flex" justifyContent="space-between">
                  <Typography>活跃警报:</Typography>
                  <Typography variant="h6" color="error">
                    {alerts.filter(a => a.status === 'ACTIVE').length}
                  </Typography>
                </Box>
                <Box display="flex" justifyContent="space-between">
                  <Typography>已解决警报:</Typography>
                  <Typography variant="h6" color="success">
                    {alerts.filter(a => a.status === 'RESOLVED').length}
                  </Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={8}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                筛选条件
              </Typography>
              <Box display="flex" gap={2} alignItems="center">
                <FormControl sx={{ minWidth: 120 }}>
                  <InputLabel>状态</InputLabel>
                  <Select
                    value={statusFilter}
                    label="状态"
                    onChange={(e) => setStatusFilter(e.target.value)}
                  >
                    <MenuItem value="ALL">全部</MenuItem>
                    <MenuItem value="ACTIVE">活跃</MenuItem>
                    <MenuItem value="RESOLVED">已解决</MenuItem>
                    <MenuItem value="PENDING">待处理</MenuItem>
                  </Select>
                </FormControl>
                <TextField
                  placeholder="搜索警报..."
                  variant="outlined"
                  size="small"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  InputProps={{
                    startAdornment: <Search />,
                  }}
                />
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Box mt={3}>
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              警报列表
            </Typography>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>警报类型</TableCell>
                    <TableCell>描述</TableCell>
                    <TableCell>车牌号</TableCell>
                    <TableCell>车辆ID</TableCell>
                    <TableCell>严重程度</TableCell>
                    <TableCell>状态</TableCell>
                    <TableCell>创建时间</TableCell>
                    <TableCell>操作</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {filteredAlerts.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} align="center">
                        <Typography color="textSecondary">
                          暂无警报数据
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredAlerts.map((alert) => (
                      <TableRow key={alert.id}>
                        <TableCell>{formatAlertType(alert.alertType) || '未知类型'}</TableCell>
                        <TableCell>{alert.description || '无描述'}</TableCell>
                        <TableCell>{alert.vehiclePlate || '无车牌号'}</TableCell>
                        <TableCell>{alert.vehicleId || '无车辆ID'}</TableCell>
                        <TableCell>
                          <Chip
                            label={formatSeverity(alert.severity)}
                            color={getSeverityColor(alert.severity)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          <Chip
                            icon={getStatusIcon(alert.status)}
                            label={alert.status}
                            color={getStatusColor(alert.status)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          {new Date(alert.createdAt).toLocaleString('zh-CN')}
                        </TableCell>
                        <TableCell>
                          {alert.status === 'ACTIVE' && (
                            <Button
                              size="small"
                              variant="outlined"
                              color="success"
                              onClick={() => {
                                setSelectedAlert(alert);
                                setOpenDialog(true);
                              }}
                            >
                              处理
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </CardContent>
        </Card>
      </Box>

      <Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
        <DialogTitle>处理警报</DialogTitle>
        <DialogContent>
          <Typography variant="body1" gutterBottom>
            确定要将此警报标记为已解决吗？
          </Typography>
          <Typography variant="body2" color="textSecondary">
            标题: {selectedAlert?.title}
          </Typography>
          <Typography variant="body2" color="textSecondary">
            描述: {selectedAlert?.description}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button
            onClick={() => handleResolveAlert(selectedAlert?.id)}
            color="success"
            variant="contained"
          >
            确认解决
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default EmergencyAlerts;